package com.ztn.iot.zhonghaichi2.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ztn.iot.zhonghaichi2.entity.IotDeviceEntity;
import com.ztn.iot.zhonghaichi2.mapper.IotDeviceMapper;
import com.ztn.iot.zhonghaichi2.service.IIotDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class IotDeviceServiceImpl implements IIotDeviceService {

    @Autowired
    private IotDeviceMapper iotDeviceMapper;

    @Override
    public IotDeviceEntity get(int id) {
        return iotDeviceMapper.selectById(id);
    }

    @Override
    public IotDeviceEntity getByDeviceCode(String deviceCode) {
        LambdaQueryWrapper<IotDeviceEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(IotDeviceEntity::getDeviceCore, deviceCode);
        queryWrapper.last("LIMIT 1");
        return iotDeviceMapper.selectOne(queryWrapper);
    }

    @Override
    public int insertOrUpdate(IotDeviceEntity iotDeviceEntity) {
        IotDeviceEntity iotDeviceDb;
        if (null != iotDeviceEntity.getId()) {
            iotDeviceDb = get(iotDeviceEntity.getId());
        } else if (StringUtils.hasText(iotDeviceEntity.getDeviceCore())) {
            iotDeviceDb = getByDeviceCode(iotDeviceEntity.getDeviceCore());
        } else {
            new IotDeviceEntity().paramWorry();
            return 0;
        }
        if (null == iotDeviceDb) {
            return insert(iotDeviceEntity);
        } else {
            iotDeviceEntity.setId(iotDeviceDb.getId());
            return update(iotDeviceEntity);
        }
    }

    @Override
    public int insert(IotDeviceEntity iotDeviceEntity) {
        return iotDeviceMapper.insert(iotDeviceEntity);
    }

    @Override
    public int update(IotDeviceEntity iotDeviceEntity) {
        return iotDeviceMapper.updateById(iotDeviceEntity);
    }

    @Override
    public List<IotDeviceEntity> listAll() {
        return iotDeviceMapper.selectList(null);
    }
}
